import requests
from project.settings_common import APPLET_CONFIG


class SpeechApplet(APPLET_CONFIG):

    def get_access_token(self, appid, secret):
        """
        get access token
        @param appid:
        @param grant_type:
        @param secret:
        @return:
        """
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}"
        res = requests.get(url.format(appid, secret)).json()
        return res

    def send_template(self, access_token, touser, template_id, t_data, page=None):
        """
        send_template
        @param access_token:
        @param touser: open_id
        @param template_id:
        @param t_data: template_data
        @param page:
        @param miniprogram_state: developer为开发版；trial为体验版；formal为正式版；默认为正式版
        @return:
        """
        url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}'.format(access_token)
        data = {
            "access_token": access_token,
            "touser": touser,
            "template_id": template_id,
            "page": page,
            "data": t_data,
            "miniprogram_state": SpeechApplet.MINIPROGRAM_STATE
        }
        res = requests.post(url, json=data).json()
        return res

    def generate_t_data(self, values1, values2, values3, values4):
        """
        生成模板参数
        @param values1:
        @param values2:
        @param values3:
        @param values4:
        @return:
        """
        return {
            "thing1": {
                "value": values1
            },
            "thing2": {
                "value": values2
            },
            "thing3": {
                "value": values3
            },
            "thing4": {
                "value": values4
            }
        }

    def generate_QR_code(self, access_token, scene, page=None, rgb=None):
        """
        生成小程序码
        @param access_token:
        @param scene:"share_code=xxx,channel=xxx,active_user_id=22"
        @param page:主页
        @param check_path:bool
        @param env_version: 正式版为"release"，体验版为"trial"，开发版为"develop"
        @param rgb: 颜色 {"r":"xxx","g":"xxx","b":"xxx"}
        @return:
        """
        url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}".format(access_token)
        data = {
            "scene": scene,
            "page": page,
            "check_path": False,
            "env_version": SpeechApplet.ENV_VERSION,
            "is_hyaline": False,
            'line_color': rgb,
            'auto_color': False if rgb else True
        }
        res = requests.post(url, json=data)
        return res

    def generate_url_scheme(self, access_token, is_expire, expire_type, path, query, expire_interval):
        """
        获取小程序 scheme 码
        @param access_token:
        @param is_expire: 是否过期 False True
        @param expire_type: 失效时间：0，失效间隔天数：1
        @param path: 小程序页面路径
        @param query:
        @param expire_interval: 过去天数
        @param env_version: 正式版为"release"，体验版为"trial"，开发版为"develop"
        @return:
        """
        url = "https://api.weixin.qq.com/wxa/generatescheme?access_token={}".format(access_token)
        data = {
            "jump_wxa": {
                "path": path,
                "query": query,
                "env_version": SpeechApplet.ENV_VERSION,
            },
            "is_expire": is_expire,
            "expire_type": expire_type,
            "expire_interval": expire_interval,
        }
        res = requests.post(url, json=data)
        return res

    def decrypt_get_phone(self, session_key, iv, encryptedData):
        """
        解密获取手机号
        @param session_key:
        @param iv:
        @param encryptedData:
        @return:
        """
        import base64
        import json
        from Crypto.Cipher import AES
        # base64 decode
        sessionKey = base64.b64decode(session_key)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))

        if decrypted['watermark']['appid'] != APPLET_CONFIG.APPID:
            raise Exception('Invalid Buffer')

        return decrypted

    def _unpad(self, s):
        return s[:-ord(s[len(s)-1:])]